package com.wyg.epdata.config;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author: WangYongGan
 * @Date: 2022/3/13 0:15
 * @Description:
 */
@Configuration
public class ElasticSearchConfig {
    public RestClient getRestClient() {
        final CredentialsProvider credentialsProvider =
                new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials("elastic", "wyg123"));

        RestClientBuilder builder = RestClient.builder(
                        new HttpHost("114.55.253.244", 9200))
                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(
                            HttpAsyncClientBuilder httpClientBuilder) {
                        return httpClientBuilder
                                .setDefaultCredentialsProvider(credentialsProvider);
                    }
                });
        return builder.build();
    }

    @Bean
    public ElasticsearchClient getClient() {
        //创建restcilent
        RestClient restClient = getRestClient();
        //驼峰
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
        final JacksonJsonpMapper jacksonJsonpMapper = new JacksonJsonpMapper(objectMapper);
        //传出曾(restclient,jsonMapper)
        ElasticsearchTransport transport = new RestClientTransport(restClient, jacksonJsonpMapper);
        ElasticsearchClient client = new ElasticsearchClient(transport);
        return client;
    }
}
